package com.shop.dao;

import com.shop.model.Teacher;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class TeacherDao {
    public  Teacher login(String teacherId,String password){
        Teacher teacher = null;
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        try {
            connection = DBUtil.getConnection();
            String sql = "select * from teacher where teacherId = ? and password = ?";
            if (connection != null) {
                    preparedStatement = connection.prepareStatement(sql);
                    preparedStatement.setString(1, teacherId);
                    preparedStatement.setString(2, password);
                    resultSet = preparedStatement.executeQuery();
            }
            if (resultSet.next()) {
                teacher = new Teacher(
                        resultSet.getString("teacherId"),
                        resultSet.getString("name"),
                        resultSet.getString("subject"),
                        resultSet.getString("courseId"),
                        resultSet.getString("password"),
                        resultSet.getString("identity")
                );
            }
        }catch (SQLException e){
            e.printStackTrace();
        }finally {
            DBUtil.close(connection,preparedStatement, resultSet);
        }

        return teacher;
    }

    public Teacher search(String teacherId){
        Teacher teacher = null;
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        try {
            connection = DBUtil.getConnection();
            String sql = "select * from teacher where teacherId = ?";
            if (connection != null) {
                preparedStatement = connection.prepareStatement(sql);
                preparedStatement.setString(1, teacherId);
                resultSet = preparedStatement.executeQuery();
            }
            if (resultSet.next())
                teacher = new Teacher(
                        resultSet.getString("teacherId"),
                        resultSet.getString("name"),
                        resultSet.getString("subject"),
                        resultSet.getString("courseId"),
                        resultSet.getString("password"),
                        resultSet.getString("identity")
                );
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            DBUtil.close(connection,preparedStatement, resultSet);
        }
        return teacher;
    }
}
